<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>详情报告</title>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/font-awesome.min93e3.css?v=4.4.0"/>
<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/plugins/datapicker/bootstrap-datetimepicker.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesome-bootstrap-checkbox/0.3.7/awesome-bootstrap-checkbox.min.css" rel="stylesheet">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/style.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<style type="text/css">
body{font-size: 14px;}.dataTables_info {font-size: 12px}.dataTables_paginate {font-size: 12px;}
table#channelTable tr{border: 1px solid #eee}
.radio{margin-top: 0;}
.radio-primary input[type="radio"] + label::after {background-color: #1ab394;}
.radio-primary input[type="radio"]:checked + label::after {background-color: #1ab394;}
.radio-primary input[type="radio"]:checked + label::before {border-color: #1ab394;}
</style>
</head>
<body class="gray-bg">
<div class="container-fluid">
	<div class="row" style="height: 40px;"></div>
	<div class="row" style="line-height: 34px;">
		<div class="col-sm-3">
			<div class="btn-group">
			    <button class="btn btn-primary" type="button">昨天</button>
			    <button class="btn btn-white" type="button">近1周</button>
			    <button class="btn btn-white" type="button">近1月</button>
			    <button class="btn btn-white" type="button">自定义</button>
			</div>
		</div>
		<div class="col-sm-3">
	        <div class="input-daterange input-group">
	            <input type="text" class="input-sm form-control" name="datetimepicker_start" readonly disabled style="background-color: white;height:34px;">
	            <span class="input-group-addon" style="background-color: #eeeeee;">到</span>
	            <input type="text" class="input-sm form-control" name="datetimepicker_end" readonly disabled style="background-color: white;height:34px;">
	        </div>
		</div>
		<div class="col-sm-3"></div>
		<div class="col-sm-3">
			<div class="input-group">
	            <input id="keyword" type="text" placeholder="输入名称搜索" class="form-control"> <span class="input-group-btn"> 
	            <button id="search" type="button" class="btn btn-primary">搜索</button> </span>
	        </div>
		</div>
	</div>
	<div class="row" style="height: 40px;"></div>
	<div class="row" style="background-color:white;margin:0;padding:10px 0;">
		<div class="col-sm-12">
			<div id="activityLine" style="height: 400px;"></div>
		</div>
	</div>
	<div class="row" style="height: 40px;"></div>
	<div class="row" style="background-color:white;margin:0;padding:10px 0;">
		<div class="col-sm-12">
			<h3 style="font-weight:bold;">活动统计表</h3>
		</div>
		<div class="col-sm-12">
			<table id="myTable" class="display">
				<thead>
					<tr>
						<th>日期</th>
						<th>活动打开</th>
		                <th>转化表单</th>
		                <th>核销人数</th>
		                <th>新增会员</th>
					</tr>
				</thead>
				<tbody>
				</tbody>
			</table>
		</div>
	</div>
	<div class="row" style="height: 40px;"></div>
	<div class="row" style="background-color:white;margin:0;padding:10px 0;">
		<div class="col-sm-6">
			<div id="activityPie" style="height: 400px;"></div>
		</div>
		<div class="col-sm-6">
			<div id="reportTypeBtn" class="text-right">
				<button class="btn btn-primary" type="button">活动打开</button>
				<button class="btn btn-white" type="button">转化表单</button>
				<button class="btn btn-white" type="button">核销人数</button>
				<button class="btn btn-white" type="button">新增会员</button>
			</div>
			<div style="height:300px;margin-top:20px;">
				<table id="channelTable" style="border-collapse:collapse;width:100%;height:100%;">
					<tr>
						<td style="padding-left:40px;" width="100px;"><img src="<%=path%>/images/marketing/all.png"></td>
						<td><p style="font-size:16px;font-weight:bold;">全员营销</p><span>0%</span></td>
						<td><span>0</span></td>
					</tr>
					<tr>
						<td style="padding-left:40px;" width="100px;"><img src="<%=path%>/images/marketing/sms.png"></td>
						<td><p style="font-size:16px;font-weight:bold;">短信营销</p><span>0%</span></td>
						<td><span>0</span></td>
					</tr>
					<tr>
						<td style="padding-left:40px;" width="100px;"><img src="<%=path%>/images/marketing/code.png"></td>
						<td><p style="font-size:16px;font-weight:bold;">扫码营销</p><span>0%</span></td>
						<td><span>0</span></td>
					</tr>
				</table>
			</div>
		</div>
	</div>
	<div class="row" style="height: 40px;"></div>
	<div class="row" style="background-color:white;margin:0;padding:10px 0;">
		<div class="col-sm-6">
			<h3 style="font-weight:bold;">最热活动</h3>
		</div>
		<div class="col-sm-4">
			<div class="radio radio-primary" style="display: inline-block;">
		        <input id="a" type="radio" name="topN" value="5">
		        <label for="a">top 5</label>
		    </div>
		    <div class="radio radio-primary" style="display: inline-block;margin-left: 40px;">
		        <input id="b" type="radio" name="topN" value="10" checked="checked">
		        <label for="b">top 10</label>
		    </div>
		    <div class="radio radio-primary" style="display: inline-block;margin-left: 40px;">
		        <input id="c" type="radio" name="topN" value="20">
		        <label for="c">top 20</label>
		    </div>
		</div>
		<div class="col-sm-2 text-right">
			<a href="<%=path%>/view/ui/activityHome" style="color:#1ab394;">查看更多</a>
		</div>
		<div class="col-sm-12">
			<div id="activityBar" style="height: 400px;"></div>
		</div>
	</div>
	<div class="row" style="height: 40px;"></div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="<%=path%>/hplus/js/plugins/datapicker/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="<%=path%>/hplus/js/plugins/datapicker/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/3.7.2/echarts.common.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
var path = "<%=path%>";
var startTime = "";
var endTime = "";
var groupBy = "";
var line_x_data = [];	//折线图 x 轴数据
var bar_x_data = [];	//柱状图 x 轴数据
var reportType = 0;		//报告类型；第三部分的渠道占比
var activityIdsOrder = [];
var activityId = getUrlParam("activityId");	//参数获取
var activityName = getUrlParam("activityName");	//参数获取
$.fn.dataTable.ext.errMode = 'none';
$(function(){
	var url= window.location.href;
    try {
    	activityName = url.split("?")[1].split("=")[2];
        activityName= decodeURI(activityName);
	} catch (e) {
	}
	
	$("input[name='datetimepicker_start']").datetimepicker({language:"zh-CN",format: 'yyyy-mm-dd',autoclose: true,minView:2}).on("click",function(){
        $("input[name='datetimepicker_start']").datetimepicker("setEndDate",$("input[name='datetimepicker_end']").val())
    }).on('changeDate', function(ev){
    	startTime = $("input[name='datetimepicker_start']").val();
    });
	$("input[name='datetimepicker_end']").datetimepicker({language:"zh-CN",format: 'yyyy-mm-dd',autoclose: true,minView:2}).on("click",function(){
        $("input[name='datetimepicker_end']").datetimepicker("setStartDate",$("input[name='datetimepicker_start']").val())
    }).on('changeDate', function(ev){
    	endTime = $("input[name='datetimepicker_end']").val();
    });
	
	$(".btn-group:eq(0)>button").click(function(){
		var index = $(this).index();
		var now = new Date();
		$(this).removeClass("btn-white").addClass("btn-primary").siblings().removeClass("btn-primary").addClass("btn-white");
		if(index == 0){
			now.setDate(now.getDate() - 1);
			endTime = now.Format("yyyy-MM-dd");
			startTime = endTime;
			groupBy = "hour";
		}else if(index == 1){
			now.setDate(now.getDate() - 1);
			endTime = now.Format("yyyy-MM-dd");
			now.setDate(now.getDate() - 7);
			startTime = now.Format("yyyy-MM-dd");
			groupBy = "day";
		}else if(index == 2){
			now.setDate(now.getDate() - 1);
			endTime = now.Format("yyyy-MM-dd");
			now.setDate(now.getDate() - 30);
			startTime = now.Format("yyyy-MM-dd");
			groupBy = "day";
		}else if(index == 3){
			$("input[name='datetimepicker_start']").removeAttr("disabled");
			$("input[name='datetimepicker_end']").removeAttr("disabled");
			groupBy = "day";
			return ;
		}
		$("input[name='datetimepicker_start']").attr("disabled",true);
		$("input[name='datetimepicker_end']").attr("disabled",true);
		$("input[name='datetimepicker_start']").val(startTime);
		$("input[name='datetimepicker_end']").val(endTime);
		
		init();
	});
	
	$("#search").click(function(){
		if($.trim($("#keyword").val()) == ""){
			activityId = null;
		}
		init();
	});
	
	$("#reportTypeBtn>button").click(function(){
		var index = $(this).index();
		$(this).removeClass("btn-white").addClass("btn-primary").siblings().removeClass("btn-primary").addClass("btn-white");
		if(reportType != index){
			reportType = index;
			func_activityPie();
		}
	});
	
	$(":radio[name='topN']").change(function(){
		func_activityBar();
	});
	
	$("#keyword").autocomplete({
		source: function( request, response ) {
			$.post(path+"/activity/ajaxListLikeName",{name:request.term},function(data){
				alert(data.status);
				if(data.status == "200"){
					response($.map(data.data,function(d){
						alert();
						return {value:d.name,label:d.name,activityId:d.id}
					}));
				}
			},"json");
		},
		select: function(e, u){
			activityId = u.item.activityId;
		}
	});
	
	$(".btn-group:eq(0)>button:eq(0)").click();
	$("#keyword").val(activityName);
});

function init(){
	func_activityLine();
	func_activityPie();
	func_activityBar();
}

//活动趋势图
function func_activityLine(){
	var json = {};
	json.startTime = startTime;
	json.endTime = endTime;
	json.groupBy = groupBy;
	json.activityId = activityId;
	$.post(path+"/activity/ajaxActivityLine",json,function(data){
		if(data.status == "200"){
			line_x_data = [];	//清空公共东西
			if($.fn.DataTable.isDataTable("#myTable")){
				$("#myTable").DataTable().clear().destroy();
			}
		 	var legend_data = ["活动打开","转化表单","核销人数","新增会员"];
			var x_data = [];
		 	var y_data = [];
		 	var dataZoom = [{show: false,start: 0,end: 100}];
		 	var y1 = [];
		 	var y2 = [];
		 	var y3 = [];
		 	var y4 = [];
		 	var countOpenGroup;
			var countCommitGroup;
			var countWriteoffGroup;
			var countNewMemberGroup;
			if(groupBy == "hour"){
				countOpenGroup = func_dealDataGroupHour(data.data.countOpenGroup,true);
				countCommitGroup = func_dealDataGroupHour(data.data.countCommitGroup,false);
				countWriteoffGroup = func_dealDataGroupHour(data.data.countWriteoffGroup,false);
// 				countNewMemberGroup = data.data.countNewMemberGroup;
				countNewMemberGroup = func_dealDataGroupHour(data.data.countNewMemberGroup,false);
			}else if(groupBy == "day"){
				countOpenGroup = func_dealDataGroupDay(data.data.countOpenGroup,true);
				countCommitGroup = func_dealDataGroupDay(data.data.countCommitGroup,false);
				countWriteoffGroup = func_dealDataGroupDay(data.data.countWriteoffGroup,false);
// 				countNewMemberGroup = data.data.countNewMemberGroup;
				countNewMemberGroup = func_dealDataGroupDay(data.data.countNewMemberGroup,false);
			}
			var count = 0;
			$.each(countOpenGroup,function(i,d){
				count++;
				var temp2 = countCommitGroup[i];
				var temp3 = countWriteoffGroup[i];
				var temp4 = countNewMemberGroup[i];
// 				if(temp4 == undefined){
// 					temp4 = 0;
// 				}
				y1.push(d);
				y2.push(temp2);
				y3.push(temp3);
				y4.push(temp4);
				var temp_time = i;
				if(groupBy == "hour"){
					temp_time = temp_time.substr(8)+":00——"+temp_time.substr(8)+":59";
				}
				$("#myTable>tbody").append("<tr><td>"+temp_time+"</td><td>"+d+"</td><td>"+temp2+"</td><td>"+temp3+"</td><td>"+temp4+"</td></tr>");
			});
			x_data = line_x_data;
			y_data.push({name:'活动打开',type:'line',smooth:true,data:y1});
		 	y_data.push({name:'转化表单',type:'line',smooth:true,data:y2});
		 	y_data.push({name:'核销人数',type:'line',smooth:true,data:y3});
		 	y_data.push({name:'新增会员',type:'line',smooth:true,data:y4});
		 	if(count > 24){
		 		dataZoom = [{show: true,start: 40,end: 60}];
		 	}
			func_line("activityLine","活动趋势图",legend_data,x_data,y_data,dataZoom);
			$("#myTable").DataTable({ordering:false,searching:false,lengthChange:false,language:{emptyTable: '没有数据表',info: '从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录',infoEmpty: '没有数据',lengthMenu: '每页显示 _MENU_ 条记录',loadingRecords: '正在加载数据....',processing: '正在处理数据....',zeroRecords: '没有找到匹配的记录',paginate: {first: '首页',previous: '前页',next: '后页',last: '尾页'}}});
		}
	},"json");
}

//渠道占比
function func_activityPie(){
	var json = {};
	json.startTime = startTime;
	json.endTime = endTime;
	json.reportType = reportType;
	json.activityId = activityId;
	$.post(path+"/activity/ajaxActivityPie",json,function(data){
		if(data.status == "200"){
			var legend_data = ["全员营销","短信营销","扫码营销"];
			var value_data = [];
			value_data.push({value:data.data.all,name:"全员营销"})
			value_data.push({value:data.data.sms,name:"短信营销"})
			value_data.push({value:data.data.code,name:"扫码营销"})
			func_pie("activityPie","渠道占比","渠道占比",legend_data,value_data);
			var all = data.data.all;
			var sms = data.data.sms;
			var code = data.data.code;
			var allBfb = "0%";
			var smsBfb = "0%";
			var codeBfb = "0%";
			if(all+sms+code > 0){
				allBfb = (all/(all+sms+code)*100).toFixed(2)+"%";
				smsBfb = (sms/(all+sms+code)*100).toFixed(2)+"%";
				codeBfb = (code/(all+sms+code)*100).toFixed(2)+"%";
			}
			$("#channelTable tr:eq(0)>td:eq(1)>span").text(allBfb);
			$("#channelTable tr:eq(0)>td:eq(2)>span").text(all);
			$("#channelTable tr:eq(1)>td:eq(1)>span").text(smsBfb);
			$("#channelTable tr:eq(1)>td:eq(2)>span").text(sms);
			$("#channelTable tr:eq(2)>td:eq(1)>span").text(codeBfb);
			$("#channelTable tr:eq(2)>td:eq(2)>span").text(code);
		}
	},"json");
}

//最热活动
function func_activityBar(){
	bar_x_data = [];		//清空数据
	activityIdsOrder = [];	//清空数据
	var json = {};
	json.startTime = startTime;
	json.endTime = endTime;
	json.topN = $(":radio[name='topN']:checked").val();
	$.post(path+"/activity/ajaxActivityBar",json,function(data){
		if(data.status == "200"){
			var legend_data = ["活动打开","转化表单","核销人数","新增会员"];
			var x_data = [];
		 	var y_data = [];
		 	var y1 = func_dealDataGroupActivityId(data.data.countOpenGroup,true);
			var y2 = func_dealDataGroupActivityId(data.data.countCommitGroup,false);
			var y3 = func_dealDataGroupActivityId(data.data.countWriteoffGroup,false);
			var y4 = func_dealDataGroupActivityId(data.data.countNewMemberGroup,false);
			
			x_data = bar_x_data;
			y_data.push({name:'活动打开',type:'bar',data:y1});
			y_data.push({name:'转化表单',type:'bar',data:y2});
			y_data.push({name:'核销人数',type:'bar',data:y3});
			y_data.push({name:'新增会员',type:'bar',data:y4});
		 	func_bar("activityBar","",legend_data,x_data,y_data);
		}
	},"json");
}

//处理数据，小时
function func_dealDataGroupHour(list,isX_data){
	var result = {};
	var now = new Date();
	now.setDate(now.getDate() - 1);
	var nowHour = now.getHours();
	var nowStr = now.Format("yyyyMMdd");
	for(var i = 0; i <= 23; i++){
		var key = nowStr;
		if(i<10){
			key += "0"+i;
		}else{
			key += i;
		}
		if(isX_data){
			line_x_data.push(i);
		}
		var isExist = false;
		$.each(list,function(i,d){
			if(key == d.createTimeStr){
				isExist = true;
				result[key] = d.totalCount;
				return false;
			}
		});
		if(!isExist){
			result[key] = 0;
		}
	}
	return result;
}
//处理数据，天
function func_dealDataGroupDay(list,isX_data){
	var result = {};
	var startTimeStrArr = startTime.split("-");
	var endTimeStrArr = endTime.split("-");
	var temp_start = new Date(startTimeStrArr[0],startTimeStrArr[1]-1,startTimeStrArr[2]);
	var temp_end = new Date(endTimeStrArr[0],endTimeStrArr[1]-1,endTimeStrArr[2]);
	for(var i = temp_start.getTime(); i <= temp_end.getTime(); i+= 24*60*60*1000){
		var key = new Date(i).Format("yyyyMMdd");
		if(isX_data){
			line_x_data.push(key);
		}
		var isExist = false;
		$.each(list,function(i,d){
			if(key == d.createTimeStr){
				isExist = true;
				result[key] = d.totalCount;
				return false;
			}
		});
		if(!isExist){
			result[key] = 0;
		}
	}
	return result;
}

//处理数据，按照 activityId
function func_dealDataGroupActivityId(list,isX_data){
	var result = [];
	
	if(isX_data){
		$.each(list,function(i,d){
			bar_x_data.push(d.activityName);
			activityIdsOrder.push(d.activityId);
			result.push(d.totalCount);
		});
	}else{
		console.log(activityIdsOrder);
		console.log(list);
		$.each(activityIdsOrder,function(i,d){
			var isExist = false;
			$.each(list,function(i2,d2){
				if(list instanceof Array){
					if(d == d2.activityId){
						result.push(d2.totalCount);
						isExist = true;
						return false;
					}
				}else{
					if(d == i2){
						result.push(d2);
						isExist = true;
						return false;
					}
				}
			});
			if(!isExist){
				result.push(0);
			}
		});
	}
	return result;
}

function func_line(id,title,legend_data,x_data,y_data,dataZoom){
    var myChart = echarts.init(document.getElementById(id));

    var option = {
   		title: {
   	        text: title,
   	        x: 'left'
   	    },
   		dataZoom: dataZoom,
		tooltip : {
   	        trigger: 'axis',
   	        axisPointer: {
   	            type: 'cross',
   	            label: {
   	                backgroundColor: '#6a7985'
   	            }
   	        }
   	    },
        legend: {
            data:legend_data
        },
        yAxis: {
        	type : 'value'
        },
        xAxis: {
        	data: x_data,
        	boundaryGap : false
        },
        series: y_data
    };
    
	myChart.setOption(option);
	myChart.resize();
}

function func_pie(id,title,pointName,legend_data,value_data){
    var myChart = echarts.init(document.getElementById(id));

    var option = {
   		title: {
   	        text: title,
   	        x: 'left'
   	    },
		tooltip: {
			trigger: 'item',
	        formatter: "{a} <br/>{b}: {c} ({d}%)"
	    },
//         legend: {
//             data:legend_data
//         },
        series: [
        	{
	            name:pointName,
	            type:'pie',
	            radius: ['50%', '70%'],
	            label: {
	                normal: {
	                    show: false,
	                    position: 'center'
	                },
	                emphasis: {
	                    show: true,
	                    textStyle: {
	                        fontSize: '24',
	                        fontWeight: 'bold'
	                    }
	                }
	            },
	            data:value_data
	        }
        ]
    };
    
	myChart.setOption(option);
	myChart.resize();
}

function func_bar(id,title,legend_data,x_data,y_data){
    var myChart = echarts.init(document.getElementById(id));

    var option = {
  		title: {
			text: title,
			x: 'left'
		},
		tooltip : {
			trigger: 'axis',
	        axisPointer : {
	            type : 'shadow'
	        }
	    },
        legend: {
            data:legend_data,
            orient: 'vertical',
			right:0
        },
        xAxis: {
        	data : x_data
        },
        yAxis: {
        	type : 'value'
        },
        series: y_data
    };
    
	myChart.setOption(option);
	myChart.resize();
}

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function getUrlParam(key){
	var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
</script>
</html>